var express = require('express');
var router = express.Router();
var qiniu = require('qiniu');
var config = require('./../config.json');
var colors = require('colors');
var http = require('http');
var q = require('q');
qiniu.conf.ACCESS_KEY = config.ACCESS_KEY;
qiniu.conf.SECRET_KEY = config.SECRET_KEY;


router.post('/', function (req, res) {
    var data = req.body;
    var newKey = data.key;
    var key = data.originKey;
    compress(key, newKey)
        .then(function (data) {
        res.send(data);
    });
});

function compress(key, newKey) {
    var defer = q.defer();
    var bucket = config.Bucket_Name;
    var encodedEntryURI = qiniu.util.urlsafeBase64Encode(bucket + ":" + newKey);
    var host = config.Bucket_Name + ".qiniudn.com";
    var signingStr = config.Bucket_Name + ".qiniudn.com/" + key + "?imageView2/3/w/1200/h/900/q/50|saveas/" + encodedEntryURI;
    var signingStr1 = "/" + key + "?imageView2/3/w/1200/h/900/q/50|saveas/" + encodedEntryURI;
    var signed = qiniu.util.hmacSha1(new Buffer(signingStr), config.SECRET_KEY);
    var signedSafe1 = qiniu.util.base64ToUrlSafe(signed);
    var imgUrl = signingStr1 + "/sign/" + config.ACCESS_KEY + ":" + signedSafe1;
    console.log('触发压缩程序:', imgUrl);
    http.get({
        host: host,
        port: 80,
        path: imgUrl
    }, function (res) {
            res.setEncoding('UTF-8');
            var result = "";
            res.on('data', function (data) {
                result += data;
            });
            res.on('end', function () {
                var r = JSON.parse(result);
                defer.resolve(true);
            });
        });
    return defer.promise;
}



module.exports = router;
